

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/favicon.png">
  <link rel="icon" type="image/png" href="/blog/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#fff">
  <meta name="description" content="その時を待つよ">
  <meta name="author" content="Isshiki_Hugh">
  <meta name="keywords" content="">
  <title>algorithm-CppSTL专题 - Isshiki&#39;sBlog</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/blog/lib/hint/hint.min.css" />

  
    
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/atom-one-dark.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_6peoq002giu.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/blog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.0.2"></head>


<body>
  <header style="height: 75vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/blog/">&nbsp;<strong>Isshiki修のBlog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/blog/img/default.JPG') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-11-07 08:17" pubdate>
      2019年11月7日 早上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.3k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      35
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">algorithm-CppSTL专题</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：1 年前
                
              </p>
            
            <div class="markdown-body" id="post-body">
              <h3 id="0-x-前言"><a href="#0-x-前言" class="headerlink" title="[0.x]前言"></a>[0.x]前言</h3><p>本文针对$Cpp$的$STL$容器</p>
<p>参考书目：《算法竞赛进阶指南》</p>
<p>所有容器都<strong>前闭右开</strong>（类比声明了数组a[n]后调用a[n]属于越界行为）</p>
<p>$STL$的迭代器相当于指针，语法类似，使用方式为<code>???::iterator ??=???</code></p>
<a id="more"></a>
<h3 id="目录"><a href="#目录" class="headerlink" title="目录"></a>目录</h3><ul>
<li>[0.x]前言</li>
<li>[1.x]vector</li>
<li>[2.x]queue/priority_queue</li>
<li>[3.x]deque</li>
<li>[4.x]set/multiset</li>
<li>[5.x]map</li>
<li>[6.x]bitset</li>
<li>[7.x]algorithm</li>
</ul>
<hr>
<h3 id="1-x-vector"><a href="#1-x-vector" class="headerlink" title="[1.x]vector"></a>[1.x]vector</h3><h4 id="1-1-性质"><a href="#1-1-性质" class="headerlink" title="[1.1]性质"></a>[1.1]性质</h4><ul>
<li>大小会随着元素的数量变化（节约空间）</li>
<li>支持<strong>随机访问</strong>（支持<strong>下标访问</strong>）</li>
<li>不支持$O(1)$插入</li>
</ul>
<h4 id="1-2-声明"><a href="#1-2-声明" class="headerlink" title="[1.2]声明"></a>[1.2]声明</h4><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;vector&gt;//头文件</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span>;

<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; a;<span class="hljs-comment">//a[i]中i所在的维动态伸缩</span>
<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; b[<span class="hljs-number">10</span>];<span class="hljs-comment">//b[i][j]中j所在的维动态伸缩</span>
<span class="hljs-comment">//其中&lt;int&gt;可以换成&lt;bool&gt;/&lt;char&gt;/&lt;string&gt;/....且支持结构体</span></code></pre></div>
<h4 id="1-3-x-操作"><a href="#1-3-x-操作" class="headerlink" title="[1.3.x]操作"></a>[1.3.x]操作</h4><h5 id="1-3-1-size-empty"><a href="#1-3-1-size-empty" class="headerlink" title="[1.3.1]size/empty"></a>[1.3.1]size/empty</h5><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的长度为&quot;</span> &lt;&lt; a.size();

<span class="hljs-keyword">if</span>(a.empty())&#123;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a为空&quot;</span>;
&#125;<span class="hljs-keyword">else</span>&#123;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a不为空&quot;</span>;
&#125;</code></pre></div>
<h5 id="1-3-2-clear"><a href="#1-3-2-clear" class="headerlink" title="[1.3.2]clear"></a>[1.3.2]clear</h5><div class="hljs"><pre><code class="hljs cpp">a.clear();<span class="hljs-comment">//清空vector型变量a</span></code></pre></div>
<h5 id="1-3-3-begin-end"><a href="#1-3-3-begin-end" class="headerlink" title="[1.3.3]begin/end"></a>[1.3.3]begin/end</h5><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;::iterator it = a.begin();
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的第一个元素为&quot;</span> &lt;&lt; *it;
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的第一个元素为&quot;</span> &lt;&lt; a[<span class="hljs-number">0</span>];<span class="hljs-comment">//两行等效</span>
it = a.end();
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的最后一个元素为&quot;</span> &lt;&lt; *--it;
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的最后一个元素为&quot;</span> &lt;&lt; a[a.size()<span class="hljs-number">-1</span>];<span class="hljs-comment">//两行等效</span></code></pre></div>
<h5 id="1-3-4-front-back"><a href="#1-3-4-front-back" class="headerlink" title="[1.3.4]front/back"></a>[1.3.4]front/back</h5><p>从front与begin类似，只不过一个返回元素一个返回迭代器，即<code>*a.begin()</code>与<code>a.front()</code>等效，当然也等效于<code>a[0]</code></p>
<p>而back与end略有区别，<code>*--a.end()</code>或<code>a[size()-1]</code>与<code>a.back()</code>等效</p>
<div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;::iterator it = a.begin();
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的第一个元素为&quot;</span> &lt;&lt; *it;
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的第一个元素为&quot;</span> &lt;&lt; a[<span class="hljs-number">0</span>];
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的第一个元素为&quot;</span> &lt;&lt; a.front();<span class="hljs-comment">//三行等效</span>
it = a.end();
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的最后一个元素为&quot;</span> &lt;&lt; *--it;
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的最后一个元素为&quot;</span> &lt;&lt; a[a.size()<span class="hljs-number">-1</span>];
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a的最后一个元素为&quot;</span> &lt;&lt; a.back();<span class="hljs-comment">//三行等效</span></code></pre></div>
<p>一般<code>begin/end</code>用于循环，而<code>front</code>和<code>back</code>只能用来返回顶部和底部。</p>
<h5 id="1-3-5-push-back-pop-back"><a href="#1-3-5-push-back-pop-back" class="headerlink" title="[1.3.5]push_back/pop_back"></a>[1.3.5]push_back/pop_back</h5><div class="hljs"><pre><code class="hljs cpp">a.push_back(x);<span class="hljs-comment">//把元素x插入到vector类型变量a的尾部</span>
a.pop_back;<span class="hljs-comment">//把vector类型变量a尾部元素删除</span></code></pre></div>
<h3 id="2-x-queue-priority-queue"><a href="#2-x-queue-priority-queue" class="headerlink" title="[2.x]queue/priority_queue"></a>[2.x]queue/priority_queue</h3><h4 id="2-1-性质"><a href="#2-1-性质" class="headerlink" title="[2.1]性质"></a>[2.1]性质</h4><ul>
<li>不支持随机访问</li>
<li><code>priority_queue</code>满足元素<strong>有序</strong>（默认降序，堆顶部（看作大根二叉堆）为$max$），如果储存元素类型不属于<strong>数字</strong>类型或者<strong><code>string</code></strong>类型需要<strong>定义比较规则</strong>。</li>
</ul>
<h4 id="2-2-声明"><a href="#2-2-声明" class="headerlink" title="[2.2]声明"></a>[2.2]声明</h4><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;queue&gt;//头文件</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">queue</span>;<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">priority_queue</span>;

<span class="hljs-built_in">queue</span>&lt;<span class="hljs-keyword">int</span>&gt; q1;<span class="hljs-comment">//循环队列</span>
<span class="hljs-built_in">queue</span>&lt; <span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">int</span>,<span class="hljs-keyword">int</span>&gt; &gt; q2;<span class="hljs-comment">//由于不支持随机访问，所以如果要储存多维只能通过数对，使用first()和second()来访问第一个数字和第二个数字</span>

<span class="hljs-built_in">priority_queue</span>&lt;<span class="hljs-keyword">int</span>&gt; q3;<span class="hljs-comment">//优先队列</span>
<span class="hljs-built_in">priority_queue</span>&lt; <span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">int</span>,<span class="hljs-keyword">int</span>&gt; &gt; q4;<span class="hljs-comment">//同上</span></code></pre></div>
<h4 id="2-3-x-操作"><a href="#2-3-x-操作" class="headerlink" title="[2.3.x]操作"></a>[2.3.x]操作</h4><p><strong>注意</strong>：由于循环队列和优先队列操作略有不同，所以以下变量<code>q</code>为<strong>循环队列</strong>，<code>p_q</code>为<strong>优先队列</strong>。</p>
<h5 id="2-3-1-push-pop"><a href="#2-3-1-push-pop" class="headerlink" title="[2.3.1]push/pop"></a>[2.3.1]push/pop</h5><div class="hljs"><pre><code class="hljs cpp">q.push(x);<span class="hljs-comment">//把元素x插入到queue类型变量q的尾部</span>
q.pop();<span class="hljs-comment">//把队首元素弹出</span>

p_q.push(x);<span class="hljs-comment">//把元素x插入到priority_queue类型变量p_q</span>
p_q.pop();<span class="hljs-comment">//把堆顶元素弹出，即有序数列的首元素</span></code></pre></div>
<h5 id="2-3-2-front-back-amp-top"><a href="#2-3-2-front-back-amp-top" class="headerlink" title="[2.3.2]front/back &amp; top"></a>[2.3.2]front/back &amp; top</h5><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;queue型变量q的第一个元素为&quot;</span> &lt;&lt; q.front();
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;queue型变量q的最后一个元素为&quot;</span> &lt;&lt; q.back();

<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;priority_queue型变量p_q的堆顶元素为&quot;</span> &lt;&lt; p_q.top();</code></pre></div>
<h3 id="3-x-deque"><a href="#3-x-deque" class="headerlink" title="[3.x]deque"></a>[3.x]deque</h3><p>咕咕咕</p>
<h3 id="4-x-set-multiset"><a href="#4-x-set-multiset" class="headerlink" title="[4.x]set/multiset"></a>[4.x]set/multiset</h3><h4 id="4-1-性质"><a href="#4-1-性质" class="headerlink" title="[4.1]性质"></a>[4.1]性质</h4><ul>
<li><code>set</code>储存有序集合</li>
<li><code>multist</code>储存有序多重集合</li>
<li>重载相关类似<code>priority_queue</code></li>
<li>迭代器只支持<code>++</code>和<code>--</code>，时间复杂度都在$O(logn)$，注意不要越界</li>
<li>默认<strong>升序</strong></li>
</ul>
<h4 id="4-2-声明"><a href="#4-2-声明" class="headerlink" title="[4.2]声明"></a>[4.2]声明</h4><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;set&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">set</span>;<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">multiset</span>;

<span class="hljs-built_in">set</span>&lt;<span class="hljs-keyword">int</span>&gt; s;
<span class="hljs-built_in">multiset</span>&lt;<span class="hljs-keyword">int</span>&gt; s;</code></pre></div>
<h4 id="4-3-x-操作"><a href="#4-3-x-操作" class="headerlink" title="[4.3.x]操作"></a>[4.3.x]操作</h4><p><strong>注意</strong>：<code>s</code>表示<strong>有序集合</strong>，<code>ms</code>表示<strong>有序重复集合</strong></p>
<h5 id="4-3-1-size-empty-clear"><a href="#4-3-1-size-empty-clear" class="headerlink" title="[4.3.1]size/empty/clear"></a>[4.3.1]size/empty/clear</h5><p>同理<code>vector</code></p>
<h5 id="4-3-2-begin-end"><a href="#4-3-2-begin-end" class="headerlink" title="[4.3.2]begin/end"></a>[4.3.2]begin/end</h5><p>同理<code>priority_queue</code></p>
<h5 id="4-3-3-insert"><a href="#4-3-3-insert" class="headerlink" title="[4.3.3]insert"></a>[4.3.3]insert</h5><div class="hljs"><pre><code class="hljs cpp">s.insert(x);<span class="hljs-comment">//将元素x插入到集合s中，如果s中已经存在元素x则不变化</span>

ms.insert(x);<span class="hljs-comment">//将元素x插入到集合ms中，如果s中已经存在元素x则再插入一个</span></code></pre></div>
<h5 id="4-3-4-find"><a href="#4-3-4-find" class="headerlink" title="[4.3.4]find"></a>[4.3.4]find</h5><p>$O(logn)$查找元素(返回迭代器)，不存在则返回<code>end()</code><br>有序多重集合返回第一个该元素的迭代器</p>
<div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">set</span>&lt;<span class="hljs-keyword">int</span>&gt;::iterator it = s.find(x);<span class="hljs-comment">//*it为元素x，it为其迭代器</span>
<span class="hljs-built_in">multiset</span>&lt;<span class="hljs-keyword">int</span>&gt;::iterator it = ms.find(x);<span class="hljs-comment">//*it为元素x，it为其迭代器</span></code></pre></div>
<h5 id="4-3-5-lower-bound-upper-bound"><a href="#4-3-5-lower-bound-upper-bound" class="headerlink" title="[4.3.5]lower_bound/upper_bound"></a>[4.3.5]lower_bound/upper_bound</h5><div class="hljs"><pre><code class="hljs cpp">?? = s.lower_bound(x);<span class="hljs-comment">//O(logn)查找&gt;=x的元素中最小的，返回迭代器（需要保证序列升序）</span>
?? = s.upper_bound(x)<span class="hljs-comment">//O(logn)查找&gt;x的元素中最小的，返回迭代器（需要保证序列升序）</span>

?? = ms.lower_bound(x)<span class="hljs-comment">//O(logn)查找&gt;=x的元素中最小的第一个，返回迭代器（需要保证序列升序）</span>
?? = ms.upper_bound(x)<span class="hljs-comment">//O(logn)查找&gt;x的元素中最小的第一个，返回迭代器（需要保证序列升序）</span></code></pre></div>
<p>如果需要应用在降序数列里，可以传输比较规则<code>greater&lt;int&gt;()</code>。</p>
<h5 id="4-3-6-erase"><a href="#4-3-6-erase" class="headerlink" title="[4.3.6]erase"></a>[4.3.6]erase</h5><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">set</span>&lt;<span class="hljs-keyword">int</span>&gt;::iterator it;
s.erase(it);<span class="hljs-comment">//O(logn)删除it所指向的元素</span>
ms.erase(it);<span class="hljs-comment">//O(logn)删除it所指向的元素</span>

<span class="hljs-keyword">int</span> x;
s.erase(x);<span class="hljs-comment">//O(k+logn)删除所有x元素</span>
ms.erase(x);<span class="hljs-comment">//O(k+logn)删除所有x元素</span></code></pre></div>
<h5 id="4-3-7-count"><a href="#4-3-7-count" class="headerlink" title="[4.3.7]count"></a>[4.3.7]count</h5><div class="hljs"><pre><code class="hljs cpp">s.count(x);<span class="hljs-comment">//返回集合s中等于x的元素的个数</span>
ms.count(x);<span class="hljs-comment">//返回集合s中等于x的元素的个数</span></code></pre></div>
<h3 id="5-x-map"><a href="#5-x-map" class="headerlink" title="[5.x]map"></a>[5.x]map</h3><h4 id="5-1-性质"><a href="#5-1-性质" class="headerlink" title="[5.1]性质"></a>[5.1]性质</h4><ul>
<li>支持任意类型的<code>key-value</code>映射，但<code>key</code>需要有比较规则</li>
<li>迭代器解除引用以后得到二元组<code>pair&lt;key_type,value_type&gt;</code></li>
</ul>
<h4 id="5-2-声明"><a href="#5-2-声明" class="headerlink" title="[5.2]声明"></a>[5.2]声明</h4><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">map</span>&lt;<span class="hljs-built_in">string</span>,<span class="hljs-keyword">int</span>&gt; mp;<span class="hljs-comment">//string类-int类映射，可以替换类型</span></code></pre></div>
<h4 id="5-3-x-操作"><a href="#5-3-x-操作" class="headerlink" title="[5.3.x]操作"></a>[5.3.x]操作</h4><h5 id="5-3-1-size-empty-clear-begin-end"><a href="#5-3-1-size-empty-clear-begin-end" class="headerlink" title="[5.3.1]size/empty/clear/begin/end"></a>[5.3.1]size/empty/clear/begin/end</h5><p>同前</p>
<h5 id="5-3-2-insert-erase"><a href="#5-3-2-insert-erase" class="headerlink" title="[5.3.2]insert/erase"></a>[5.3.2]insert/erase</h5><p>同前<br><code>insert</code>需要插入对应的二元组<br><code>erase</code>可以是二元组或迭代器</p>
<div class="hljs"><pre><code class="hljs cpp">mp.insert(<span class="hljs-built_in">make_pair</span>(x,y));<span class="hljs-comment">//插入x-y的映射</span>

mp.erase(<span class="hljs-built_in">make_pair</span>(x,y));<span class="hljs-comment">//删除x-y的映射</span>
mp.erase(it);<span class="hljs-comment">//删除it所指的映射</span></code></pre></div>
<h5 id="5-3-3-find"><a href="#5-3-3-find" class="headerlink" title="[5.3.3]find"></a>[5.3.3]find</h5><p>同前，$O(logn)$查找目标为key</p>
<h5 id="5-3-4"><a href="#5-3-4" class="headerlink" title="[5.3.4][]"></a>[5.3.4]<code>[]</code></h5><div class="hljs"><pre><code class="hljs cpp">mp[str] = a;
mp[ch] = flag;
...
<span class="hljs-comment">//使用[]前最好先用find查询是否存在映射，否则会浪费空间</span></code></pre></div>
<h3 id="6-x-bitset"><a href="#6-x-bitset" class="headerlink" title="[6.x]bitset"></a>[6.x]bitset</h3><p>咕咕咕</p>
<h3 id="7-x-algorithm"><a href="#7-x-algorithm" class="headerlink" title="[7.x]algorithm"></a>[7.x]algorithm</h3><p><strong>注意</strong>：以下操作都作用在序列上，都在<strong>前闭后开</strong>区间$[l,r)$中的元素进行操作</p>
<h4 id="7-1-x-操作"><a href="#7-1-x-操作" class="headerlink" title="[7.1.x]操作"></a>[7.1.x]操作</h4><h5 id="7-1-1-reserve"><a href="#7-1-1-reserve" class="headerlink" title="[7.1.1]reserve"></a>[7.1.1]reserve</h5><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; a;
reverse(a.begin(),a.end());<span class="hljs-comment">//翻转vector类型变量a</span>

<span class="hljs-keyword">int</span> b[<span class="hljs-number">100</span>];
reverse(b+<span class="hljs-number">1</span>,b+n+<span class="hljs-number">1</span>);<span class="hljs-comment">//翻转数组b中1~n的序列</span></code></pre></div>
<h5 id="7-1-2-unique"><a href="#7-1-2-unique" class="headerlink" title="[7.1.2]unique"></a>[7.1.2]unique</h5><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; a;
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量a去重后的元素个数为&quot;</span> &lt;&lt; unique(a.begin(),a.end()) - a.begin();

<span class="hljs-keyword">int</span> b[<span class="hljs-number">100</span>];
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;数组b去重后的元素个数为&quot;</span> &lt;&lt; unique(b+<span class="hljs-number">1</span>,b+n+<span class="hljs-number">1</span>) - (b+<span class="hljs-number">1</span>);<span class="hljs-comment">//去重后元素存放在下标1~n，未去重的部分保留</span></code></pre></div>
<h5 id="7-1-3-random-shuffle"><a href="#7-1-3-random-shuffle" class="headerlink" title="[7.1.3]random_shuffle"></a>[7.1.3]random_shuffle</h5><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; a;
random_shuffle(a.begin(),a.end());<span class="hljs-comment">//打乱vector类型变量a</span>

<span class="hljs-keyword">int</span> b[<span class="hljs-number">100</span>];
random_shuffle(b+<span class="hljs-number">1</span>,b+n+<span class="hljs-number">1</span>);<span class="hljs-comment">//打乱数组b中1~n的序列</span></code></pre></div>
<h5 id="7-1-4-next-permutation-prev-permutation"><a href="#7-1-4-next-permutation-prev-permutation" class="headerlink" title="[7.1.4]next_permutation/prev_permutation"></a>[7.1.4]next_permutation/prev_permutation</h5><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-comment">//按照字典序输出全排列(起始数列升序)</span>
<span class="hljs-keyword">do</span>&#123;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++)&#123;
        <span class="hljs-built_in">cout</span> &lt;&lt; a[i] &lt;&lt; <span class="hljs-string">&quot; &quot;</span>;
    &#125;<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
&#125;<span class="hljs-keyword">while</span>(next_permutation(a+<span class="hljs-number">1</span>,a+n+<span class="hljs-number">1</span>));

<span class="hljs-comment">//按照字典序倒着输出全排列(起始数列降序)</span>
<span class="hljs-keyword">do</span>&#123;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++)&#123;
        <span class="hljs-built_in">cout</span> &lt;&lt; a[i] &lt;&lt; <span class="hljs-string">&quot; &quot;</span>;
    &#125;<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
&#125;<span class="hljs-keyword">while</span>(prev_permutation(a+<span class="hljs-number">1</span>,a+n+<span class="hljs-number">1</span>));</code></pre></div>
<h5 id="7-1-5-sort"><a href="#7-1-5-sort" class="headerlink" title="[7.1.5]sort"></a>[7.1.5]sort</h5><p>略</p>
<h5 id="7-1-6-lower-bound-upper-bound"><a href="#7-1-6-lower-bound-upper-bound" class="headerlink" title="[7.1.6]lower_bound/upper_bound"></a>[7.1.6]lower_bound/upper_bound</h5><p>同前，需要数列<strong>升序</strong></p>
<p>如果需要应用在降序数列里，可以传输比较规则<code>greater&lt;int&gt;()</code>。</p>
<div class="hljs"><pre><code class="hljs cpp"><span class="hljs-keyword">int</span> i = lower_bound(a+<span class="hljs-number">1</span>,a+n+<span class="hljs-number">1</span>,x) - a;<span class="hljs-comment">//输出升序数组a中1~n中&gt;=x的第一个数的下标</span>

<span class="hljs-keyword">int</span> j = upper_bound(a+<span class="hljs-number">1</span>,a+n+<span class="hljs-number">1</span>,x) - a;<span class="hljs-comment">//输出升序数组a中1~n中&gt;x的第一个数的下标</span>

<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量b中大于等于x的最大整数&quot;</span> &lt;&lt; *lower_bound(b.begin(),b.end(),x) &lt;&lt; <span class="hljs-built_in">endl</span>;
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;vector型变量b中小于等于x的最大整数&quot;</span> &lt;&lt; *--upper_bound(b.begin(),b.end(),x) &lt;&lt; <span class="hljs-built_in">endl</span>;</code></pre></div>
<h5 id="7-1-7-unique"><a href="#7-1-7-unique" class="headerlink" title="[7.1.7]unique"></a>[7.1.7]unique</h5><p><code>unique</code>函数用于去重，使用该函数之前一般先排序。下面只讲不涉及迭代器的常规用法。</p>
<div class="hljs"><pre><code class="hljs cpp"><span class="hljs-built_in">std</span>::sort(a+<span class="hljs-number">1</span>,a+n+<span class="hljs-number">1</span>); <span class="hljs-comment">// 先决条件，排序</span>
<span class="hljs-keyword">int</span> cnt = <span class="hljs-built_in">std</span>::unique(a+<span class="hljs-number">1</span>,a+n+<span class="hljs-number">1</span>) - a - <span class="hljs-number">1</span>; <span class="hljs-comment">// 实现去除重复元素的同时达到了得到去重后元素种树cnt的效果</span>
<span class="hljs-comment">/*</span>
<span class="hljs-comment">运行前：</span>
<span class="hljs-comment">a = &#123;0,1,2,3,3,4&#125; , n = 5;</span>
<span class="hljs-comment">运行后：</span>
<span class="hljs-comment">a = &#123;0,1,2,3,4,4&#125; , n = 5 , cnt = 4;</span>
<span class="hljs-comment">*/</span></code></pre></div>
<link rel="stylesheet" href="/blog/css/spoiler.css" type="text/css"><script src="/blog/js/spoiler.js" type="text/javascript" async></script>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/blog/categories/%E7%AE%97%E6%B3%95/">算法</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/blog/tags/%E7%AE%97%E6%B3%95/">算法</a>
                    
                      <a class="hover-with-bg" href="/blog/tags/%E4%BF%A1%E5%A5%A5/">信奥</a>
                    
                      <a class="hover-with-bg" href="/blog/tags/%E4%B8%93%E9%A2%98/">专题</a>
                    
                      <a class="hover-with-bg" href="/blog/tags/Cpp/">Cpp</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">未经允许禁止用于商业用途，转载请标注出处和作者！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2019/11/07/algdp/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">algorithm-dp动态规划专题</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2019/11/06/PLAN2019/">
                        <span class="hidden-mobile">PLAN2019</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments">
                
                <!-- 来必力City版安装代码 -->
<div id="lv-container" data-id="city" data-uid="MTAyMC80ODI4NS8yNDc3OQ==">
  <script type="text/javascript">
     (function(d, s) {
         var j, e = d.getElementsByTagName(s)[0];
  
         if (typeof LivereTower === 'function') { return; }
  
         j = d.createElement(s);
         j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
         j.async = true;
  
         e.parentNode.insertBefore(j, e);
     })(document, 'script');
  </script>
  <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
  </div>
  <!-- City版安装代码已完成 -->
              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->

  <div class="col-lg-7 mx-auto nopadding-md">
    <div class="container custom post-content mx-auto">
      <p><center><b>(っ*´Д`)っ㊖ <font color="darkblue">  疯 狂 暗 示  </font>(っ*´Д`)っ㊖</b></center></p><center><img src="https://pic.downk.cc/item/5f3bd3b414195aa59408fb13.png" srcset="/blog/img/loading.gif" width="50%" height="50%"/></center>
    </div>
  </div>


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  
    <!-- APlayer 音乐播放器 -->
    <div id="aplayer"></div>
    <script defer src="https://cdn.staticfile.org/aplayer/1.10.1/APlayer.min.js" ></script>
<link  rel="stylesheet" href="https://cdn.staticfile.org/aplayer/1.10.1/APlayer.min.css" />
<script type="text/javascript">
  var oldLoadAp = window.onload;
  window.onload = function () {
    oldLoadAp && oldLoadAp();

    new APlayer({
      container: document.getElementById('aplayer'),
      fixed: true,
      autoplay: 'false' === 'true',
      loop: 'all',
      order: 'random',
      theme: '#708090',
      preload: 'none',
      audio: [{"name":"SLEEPWALK","artist":"冰镇豆沙君","url":"http://music.163.com/song/media/outer/url?id=1417007045.mp3","cover":"/img/cover.jpg"},{"name":"雨き声残响","artist":"冰镇豆沙君","url":"http://music.163.com/song/media/outer/url?id=1318309030.mp3","cover":"/img/cover.jpg"},{"name":"春を告げる","artist":"茶玖","url":"http://music.163.com/song/media/outer/url?id=1460240705.mp3","cover":"/img/cover.jpg"},{"name":"ベクターフィッシュ","artist":"茶玖","url":"http://music.163.com/song/media/outer/url?id=1445572300.mp3","cover":"/img/cover.jpg"},{"name":"红莲华","artist":"噢耶","url":"http://music.163.com/song/media/outer/url?id=1397590357.mp3","cover":"/img/cover.jpg"},{"name":"横竖撇点折","artist":"噢耶","url":"http://music.163.com/song/media/outer/url?id=1421414775.mp3","cover":"/img/cover.jpg"},{"name":"たぶん","artist":"真央","url":"http://music.163.com/song/media/outer/url?id=1464762744.mp3","cover":"/img/cover.jpg"},{"name":"夜に駆ける","artist":"真央","url":"http://music.163.com/song/media/outer/url?id=1461930738.mp3","cover":"/img/cover.jpg"},{"name":"Alice","artist":"yakuri","url":"http://music.163.com/song/media/outer/url?id=1431092750.mp3","cover":"/img/cover.jpg"},{"name":"起风了","artist":"yakuri","url":"http://music.163.com/song/media/outer/url?id=1367440424.mp3","cover":"/img/cover.jpg"}]
    });
  }
</script>

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/debouncer.js" ></script>
<script  src="/blog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/blog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/blog/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 6,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "algorithm-CppSTL专题&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 50,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>





  <script  src="/blog/js/local-search.js" ></script>
  <script>
    var path = "/blog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  



  
  
    <script type="text/javascript">
      //定义获取词语下标
      var a_idx = 0;
      jQuery(document).ready(function ($) {
        //点击body时触发事件
        $("body").click(function (e) {
          //需要显示的词语
          var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善");
          //设置词语给span标签
          var $i = $("<span/>").text(a[a_idx]);
          //下标等于原来下标+1  余 词语总数
          a_idx = (a_idx + 1) % a.length;
          //获取鼠标指针的位置，分别相对于文档的左和右边缘。
          //获取x和y的指针坐标
          var x = e.pageX, y = e.pageY;
          //在鼠标的指针的位置给$i定义的span标签添加css样式
          $i.css({
            "z-index": 999,
            "top": y - 20,
            "left": x,
            "position": "absolute",
            "font-weight": "bold",
            "color": rand_color()
          });
          // 随机颜色
          function rand_color() {
            return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
          }
          //在body添加这个标签
          $("body").append($i);
          //animate() 方法执行 CSS 属性集的自定义动画。
          //该方法通过CSS样式将元素从一个状态改变为另一个状态。CSS属性值是逐渐改变的，这样就可以创建动画效果。
          //详情请看http://www.w3school.com.cn/jquery/effect_animate.asp
          $i.animate({
            //将原来的位置向上移动180
            "top": y - 180,
            "opacity": 0
            //1500动画的速度
          }, 1500, function () {
            //时间到了自动删除
            $i.remove();
          });
        });
      })
      ;
    </script>
  














<script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"hHeadPos":0.5,"vHeadPos":0.618,"jsonPath":"/blog/live2dw/assets/assets/hijiki.model.json"},"display":{"superSample":1,"width":150,"height":300,"position":"right","hOffset":0,"vOffset":-20},"mobile":{"show":true,"scale":1},"react":{"opacityDefault":0.7,"opacityOnHover":0.2},"log":false});</script></body>
</html>
